<template>
  <div class="login-container">
    <div class="login-box">
      <h2>用户登录</h2>
      <form @submit.prevent="handleLogin">
        <div class="form-group">
          <label for="username">用户名</label>
          <input 
            type="text" 
            id="username" 
            v-model="username" 
            required
            placeholder="请输入用户名"
          >
        </div>
        <div class="form-group">
          <label for="password">密码</label>
          <input 
            type="password" 
            id="password" 
            v-model="password" 
            required
            placeholder="请输入密码"
          >
        </div>
        <div class="form-group">
          <label for="userType">用户类型</label>
          <select id="userType" v-model="userType" required>
            <option value="user">普通用户</option>
            <option value="admin">管理员</option>
          </select>
        </div>
        <div class="error-message" v-if="errorMessage">
          {{ errorMessage }}
        </div>
        <button type="submit" :disabled="isLoading">
          {{ isLoading ? '登录中...' : '登录' }}
        </button>
      </form>
      <p class="register-link">
        还没有账号？ <router-link to="/register">立即注册</router-link>
      </p>
    </div>
  </div>
</template>

<script>
import { API_ENDPOINTS } from '../api/config';
import axios from 'axios';

export default {
  name: 'UserLogin',
  data() {
    return {
      username: '',
      password: '',
      userType: 'user',
      errorMessage: '',
      isLoading: false
    };
  },
  methods: {
    async handleLogin() {
      this.isLoading = true;
      this.errorMessage = '';

      try {
        console.log('发送登录请求:', {
          username: this.username,
          password: this.password,
          userType: this.userType
        });

        const response = await axios.post(API_ENDPOINTS.AUTH.LOGIN, {
          username: this.username,
          password: this.password,
          role: this.userType
        });

        console.log('登录响应:', response.data);

        if (response.data.token) {
          // 保存用户信息和token
          localStorage.setItem('user', JSON.stringify(response.data.user));
          localStorage.setItem('token', response.data.token);
          
          // 设置axios默认headers
          axios.defaults.headers.common['Authorization'] = `Bearer ${response.data.token}`;
          
          console.log('登录成功，准备跳转');
          
          // 根据用户类型跳转到不同页面
          if (response.data.user.role === 'admin') {
            await this.$router.push('/admin/dashboard');
          } else {
            await this.$router.push('/dashboard/drugs');
          }
        }
      } catch (error) {
        console.error('登录失败:', error);
        if (error.response) {
          console.error('错误响应:', error.response.data);
          this.errorMessage = error.response.data.message || '登录失败，请检查用户名和密码';
        } else if (error.request) {
          console.error('请求错误:', error.request);
          this.errorMessage = '网络错误，请检查网络连接';
        } else {
          console.error('其他错误:', error.message);
          this.errorMessage = '发生错误，请稍后重试';
        }
      } finally {
        this.isLoading = false;
      }
    }
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: #f8f9fa;
}

.login-box {
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  width: 100%;
  max-width: 400px;
}

h2 {
  text-align: center;
  color: #2c3e50;
  margin-bottom: 30px;
}

.form-group {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 5px;
  color: #2c3e50;
}

input, select {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
}

input:focus, select:focus {
  outline: none;
  border-color: #42b983;
}

button {
  width: 100%;
  padding: 12px;
  background: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:hover {
  background: #3aa876;
}

button:disabled {
  background: #a8d5c2;
  cursor: not-allowed;
}

.error-message {
  color: #dc3545;
  margin-bottom: 15px;
  text-align: center;
}

.register-link {
  text-align: center;
  margin-top: 20px;
  font-size: 0.9em;
}

.register-link a {
  color: #42b983;
  text-decoration: none;
}

.register-link a:hover {
  text-decoration: underline;
}
</style>